Public Partial Class FrmReciboABM
    Inherits System.Web.UI.Page
    Public Cliente As CapaDeNegocios.nCliente = New CapaDeNegocios.nCliente
    Public Facturas As CapaDeNegocios.nFactura = New CapaDeNegocios.nFactura
    Public NotaDeCredito As CapaDeNegocios.nNotaDeCredito = New CapaDeNegocios.nNotaDeCredito
    Public NotaDeDebito As CapaDeNegocios.nNotaDeDebito = New CapaDeNegocios.nNotaDeDebito
    Public Recibo As CapaDeNegocios.nRecibo = New CapaDeNegocios.nRecibo
    Public DetalleRecibo As CapaDeNegocios.nDetalleRecibo = New CapaDeNegocios.nDetalleRecibo

    Dim DtsFacturas As DataSet
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Login") = "Anonimo" Then
            Response.Redirect("/")
        End If

        If Not Page.IsPostBack Then
            LimpiarCampos()
            LlenarCboCliente()
            DtsFacturas = New DataSet()
            DtsFacturas.Tables.Add("TblFactura")
            DtsFacturas.Tables(0).Columns.Add("IdFactura")
            DtsFacturas.Tables(0).Columns.Add("IdNotaDeCredito")
            DtsFacturas.Tables(0).Columns.Add("IdNotaDeDebito")
            DtsFacturas.Tables(0).Columns.Add("Tipo")
            DtsFacturas.Tables(0).Columns.Add("Numero")
            DtsFacturas.Tables(0).Columns.Add("Fecha")
            DtsFacturas.Tables(0).Columns.Add("Total")
            Session("DtsFacturas") = DtsFacturas
            LnkListadoFacturas.OnClientClick = "javascript:var popup = window.open('FrmListadoRecibos.aspx',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            LnkImputaciones.OnClientClick = "javascript:var popup = window.open('FrmImputaciones.aspx?Importe=" + LblTotal.Text + "',(new Date().getTime()),'Width=500,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            'LnkImputaciones.OnClientClick = "javascript:var popup = window.open('FrmImputaciones.aspx?Importe=" + LblTotal.Text + "',(new Date().getTime()),'Width=400,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
        End If
    End Sub
    Sub LimpiarCampos()
        '        TxtNumero.Text = "00000000"
        '        TxtNumero.Enabled = False}
        LblFecha.Text = Now.Date.ToShortDateString()

    End Sub
    Sub LlenarCboCliente()
        CboClientes.Items.Clear()
        CboClientes.Items.Add(New ListItem("Seleccione...", -1))
        CboClientes.DataSource = Cliente.Listar("", "", "", "", "", "", "", "", "", "", "", "")
        CboClientes.DataTextField = "RazonSocial"
        CboClientes.DataValueField = "CodigoCliente"
        CboClientes.DataBind()
        If CboClientes.Items.Count > 1 Then
            CboClientes.SelectedIndex = 0
            LlenarFacturas()
        End If
    End Sub
    Sub LlenarFacturas()
        CboFacturas.Items.Clear()
        CboFacturas.Items.Add(New ListItem("Seleccione...", -1))
        CboFacturas.DataSource = Facturas.BuscarFiltrado("", "", "", "EMITIDA", "", "", "", CboClientes.SelectedValue.ToString(), "", "")
        CboFacturas.DataTextField = "Numero"
        CboFacturas.DataValueField = "IdFactura"
        CboFacturas.DataBind()
        CboFacturas.Enabled = CboFacturas.Items.Count > 1
        If CboFacturas.Items.Count > 1 Then
            CboFacturas.SelectedIndex = 0
        End If
    End Sub
    Protected Sub CboClientes_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CboClientes.SelectedIndexChanged
        LlenarFacturas()
    End Sub
    Sub AgregarNotasDeCredito(ByVal IdFactura As String)
        Dim dtsNotaDeCredito As DataSet = NotaDeCredito.BuscarFiltrado("", "", "", "", IdFactura, "", "")
        For Each row As DataRow In dtsNotaDeCredito.Tables(0).Rows
            If row("Estado").ToString() <> "ANULADA" Then
                Dim dr As DataRow
                dr = DtsFacturas.Tables(0).NewRow()
                dr("Numero") = row("Numero").ToString()
                dr("Tipo") = "NC"
                dr("IdFactura") = "0"
                dr("IdNotaDeCredito") = row("IdNotaDeCredito").ToString()
                dr("IdNotaDeDebito") = "0"
                dr("Fecha") = row("Fecha").ToString()
                dr("Total") = row("Total").ToString()
                DtsFacturas.Tables(0).Rows.Add(dr)
                LblTotal.Text = (CDbl(LblTotal.Text) - CDbl(dr("Total").ToString())).ToString()
            End If
        Next
    End Sub

    Sub AgregarNotasDeDebito(ByVal IdFactura As String)
        Dim dtsNotaDeDebito As DataSet = NotaDeDebito.BuscarFiltrado("", "", "", "", IdFactura, "", "")
        For Each row As DataRow In dtsNotaDeDebito.Tables(0).Rows
            If row("Estado").ToString() <> "ANULADA" Then
                Dim dr As DataRow
                dr = DtsFacturas.Tables(0).NewRow()
                dr("Numero") = row("Numero").ToString()
                dr("Tipo") = "ND"
                dr("IdFactura") = "0"
                dr("IdNotaDeCredito") = "0"
                dr("IdNotaDeDebito") = row("IdNotaDeDebito").ToString()
                dr("Fecha") = row("Fecha").ToString()
                dr("Total") = row("Total").ToString()
                DtsFacturas.Tables(0).Rows.Add(dr)
                LblTotal.Text = (CDbl(LblTotal.Text) + CDbl(dr("Total").ToString())).ToString()
            End If
        Next
    End Sub

    Protected Sub LnkAgregarFactura_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkAgregarFactura.Click
        If (CboFacturas.Items.Count > 1) Then
            CboClientes.Enabled = False
            Dim dr As DataRow
            Dim IVA As Double = 1.21
            DtsFacturas = Session("DtsFacturas")
            dr = DtsFacturas.Tables(0).NewRow()
            dr("Numero") = CboFacturas.Items(CboFacturas.SelectedIndex).Text.ToString()
            dr("IdFactura") = CboFacturas.SelectedValue.ToString()
            dr("Tipo") = "FC"
            dr("IdNotaDeCredito") = "0"
            dr("IdNotaDeDebito") = "0"
            dr("Fecha") = Facturas.BuscarFiltrado(CboFacturas.SelectedValue.ToString(), "", "", "", "", "", "", "", "", "").Tables(0).Rows(0)("Fecha").ToString()
            dr("Total") = Facturas.BuscarFiltrado(CboFacturas.SelectedValue.ToString(), "", "", "", "", "", "", "", "", "").Tables(0).Rows(0)("Total").ToString()
            DtsFacturas.Tables(0).Rows.Add(dr)
            LblTotal.Text = (CDbl(LblTotal.Text) + CDbl(dr("Total").ToString())).ToString()
            LnkImputaciones.OnClientClick = "javascript:var popup = window.open('FrmImputaciones.aspx?Importe=" + LblTotal.Text + "',(new Date().getTime()),'Width=500,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            AgregarNotasDeCredito(CboFacturas.SelectedValue.ToString())
            AgregarNotasDeDebito(CboFacturas.SelectedValue.ToString())

            GridFacturas.DataSource = DtsFacturas
            GridFacturas.DataBind()
            CboFacturas.Enabled = False
            CboFacturas.Items(CboFacturas.SelectedIndex).Enabled = False
            Dim i As Integer
            For i = 0 To CboFacturas.Items.Count() - 1
                CboFacturas.Enabled = CboFacturas.Enabled Or CboFacturas.Items(i).Enabled
            Next
            LnkAgregarFactura.Enabled = CboFacturas.Enabled
        End If

    End Sub

    Protected Sub GridFacturas_RowDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridFacturas.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim IntLnkMasInformacion As LinkButton = e.Row.FindControl("LnkMasInformacion")
            Dim IntLnkRemover As LinkButton = e.Row.FindControl("LnkRemover")
            Dim IntLblTipo As Label = e.Row.FindControl("LblTipo")
            Dim IntIdFactura As HiddenField = e.Row.FindControl("HFIdFactura")
            IntLnkMasInformacion.OnClientClick = "javascript:var popup = window.open('FrmListadoFacturaVenta.aspx?IdFactura=" + IntIdFactura.Value.ToString() + "',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            If IntLblTipo.Text <> "FC" Then
                IntLnkRemover.Visible = False
                IntLnkMasInformacion.Visible = False
            End If
        End If
    End Sub

    Protected Sub LnkMasInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkMasInfo.Click
        If CboFacturas.Enabled Then
            Me.Response.Write("<script languaje='javascript'>var popup = window.open('FrmListadoFacturaVenta.aspx?IdFactura=" + CboFacturas.SelectedValue.ToString() + "',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')</script>")
        End If
    End Sub
 
    Sub BorrarDataset(ByVal dts As DataSet)
        If dts.Tables(0).Rows.Count() > 0 Then
            dts.Tables(0).Rows.Remove(dts.Tables(0).Rows(0))
            BorrarDataset(dts)
        End If
    End Sub
    Protected Sub GridFacturas_RowCommand(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridFacturas.RowCommand
        If e.CommandName = "Remover" Then
            CboFacturas.Items(CboFacturas.Items.IndexOf(CboFacturas.Items.FindByValue(CInt(e.CommandSource.Parent.Parent.FindControl("HFIdFactura").value.ToString())))).Enabled = True
            DtsFacturas = Session("DtsFacturas")
            Dim i As Integer = CInt(e.CommandSource.parent.parent.RowIndex)
            Dim Salir As Boolean
            Do
                If DtsFacturas.Tables(0).Rows(i)("Tipo").ToString() <> "NC" Then
                    LblTotal.Text = (CDbl(LblTotal.Text) - CDbl(DtsFacturas.Tables(0).Rows(i)("Total").ToString())).ToString()
                Else
                    LblTotal.Text = (CDbl(LblTotal.Text) + CDbl(DtsFacturas.Tables(0).Rows(i)("Total").ToString())).ToString()
                End If
                DtsFacturas.Tables(0).Rows.Remove(DtsFacturas.Tables(0).Rows(i))
                Salir = DtsFacturas.Tables(0).Rows.Count <= i
                If Not Salir Then
                    Salir = DtsFacturas.Tables(0).Rows(i)("Tipo").ToString() = "FC"
                End If
            Loop Until Salir
            GridFacturas.DataSource = DtsFacturas
            GridFacturas.DataBind()
            CboFacturas.Enabled = Not CboFacturas.Text = ""
            CboClientes.Enabled = DtsFacturas.Tables(0).Rows.Count = 0
            LnkAgregarFactura.Enabled = CboFacturas.Enabled
            If LblTotal.Text = "0" Then
                LblTotal.Text = "0,00"
                LnkImputaciones.OnClientClick = "#"
            Else
                LnkImputaciones.OnClientClick = "javascript:var popup = window.open('FrmImputaciones.aspx?Importe=" + LblTotal.Text + "',(new Date().getTime()),'Width=500,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            End If
        End If
    End Sub

    Protected Sub LinkCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkCancelar.Click
        DtsFacturas = Session("DtsFacturas")
        Session("DtsImputaciones") = ""
        BorrarDataset(DtsFacturas)
        Dim Cont As Integer
        Cont = 0
        For Cont = 0 To CboFacturas.Items.Count - 1
            CboFacturas.Items(Cont).Enabled = True
        Next
        CboClientes.Enabled = True
        CboFacturas.Enabled = True
        LblTotal.Text = "0,00"
        GridFacturas.DataSource = DtsFacturas
        GridFacturas.DataBind()
    End Sub

    Protected Function Verificar_Imputaciones(ByVal DtsImputaciones As DataSet) As Boolean
        If Not (DtsImputaciones Is Nothing) Then
            Dim total As Double
            total = CDbl(LblTotal.Text)
            For Each row As DataRow In DtsImputaciones.Tables(0).Rows
                total = total - CDbl(row("Total").ToString())
            Next
            Return total = 0
        End If
        Return False
    End Function
    Protected Sub LnkGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkGuardar.Click
        If CboClientes.SelectedValue <> -1 Then

            Dim DtsImputaciones As DataSet = Session("DtsImputaciones")
            If CDbl(LblTotal.Text) > 0 Then
                If Verificar_Imputaciones(DtsImputaciones) Then
                    Dim VarError As Boolean = False
                    If Not Recibo.Existe((LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", "")) Then
                        Dim IdRecibo As String = Recibo.Insertar((LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", ""), LblTotal.Text, CboClientes.SelectedValue.ToString(), DtsImputaciones).Tables(0).Rows(0)("IdRecibo").ToString()
                        If IdRecibo <> "" Then
                            DtsFacturas = Session("DtsFacturas")
                            For Each row As DataRow In DtsFacturas.Tables(0).Rows
                                If row("TIPO").ToString() = "FC" Then
                                    VarError = VarError Or Not DetalleRecibo.Insertar(IdRecibo, row("IdFactura").ToString())
                                    Facturas.Modificar(row("IdFactura").ToString(), "", "", "CANCELADA", "", "", "", "", "", "")
                                End If
                            Next
                            '                    VarError = VarError And Recibo.GrabarImputaciones(DtsImputaciones, IdRecibo)
                            If Not VarError Then
                                VarError = Not Recibo.GrabarImputaciones(DtsImputaciones, IdRecibo)
                            End If
                            If VarError Then
                                DetalleRecibo.Eliminar(IdRecibo, "")
                                Recibo.EliminarImputaciones(IdRecibo)
                                Recibo.Eliminar(IdRecibo)
                                For Each row As DataRow In DtsFacturas.Tables(0).Rows
                                    If row("TIPO").ToString() = "FC" Then
                                        Facturas.Modificar(row("IdFactura").ToString(), "", "", "EMITIDA", "", "", "", "", "", "")
                                    End If
                                Next
                                LblError.Text = "Error, En la insersion del remito."
                            Else
                                Session("DtsImputaciones") = ""
                                Me.Response.Redirect("FrmReciboABM.aspx")
                            End If
                        End If
                    Else
                        LblError.Text = "Error, El Remito ya existe en el sistema."
                    End If
                Else
                    LblError.Text = "Error, Las imputaciones no nivelan con el total."
                End If
            Else
                LblError.Text = "Error, El monto no puede ser 0."
            End If
        Else
            LblError.Text = "Error, El cliente debe seleccionarse."
        End If

    End Sub

    Protected Sub LinkNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkNuevo.Click
        LinkCancelar_Click(sender, e)
    End Sub

End Class